<template>
  <div>
    <DynamicTable
      :search="false"
      :data-request="loadTableData"
      :columns="columns"
      :expanded-row-keys="expandedRowKeys"
      @expand="handleExpand"
    >
      <template #toolbar>
        <a-button type="primary" @click="openMenuModal({})"> <PlusOutlined />新增 </a-button>
        <a-button type="primary" @click="handleExpandAndClose()"
          ><SwapOutlined /> 展开/折叠
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="tsx" setup>
  import { ref, h } from 'vue';
  import { cloneDeep, uniq } from 'lodash-es';
  import { PlusOutlined, SwapOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
  import {
    baseColumns,
    formatFormSortTree,
    type TableListItem,
    type TableColumnItem,
  } from '@/views/form/formSort/columns';
  import { useFormSortSchema } from '@/views/form/formSort/formSchemas';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { getFormSortList, deleteFormSort, createFormSort, editFormSort } from '@/api/form/sort';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/useFormModal';
  import { flatTree, type TreeDataItem } from '@/core/permission/utils';

  defineOptions({
    name: 'SysMenu',
  });

  const formSortTree = ref<TreeSelectProps['treeData']>([]);
  const [DynamicTable, dynamicTableInstance] = useTable({
    pagination: false,
    size: 'small',
    rowKey: 'id',
    bordered: true,
  });
  const [showModal] = useFormModal();

  const hasExpandKeys = ref<string[]>([]);
  const expandedRowKeys = ref<string[]>([]);
  const handleExpandAndClose = () => {
    if (expandedRowKeys.value.length) {
      expandedRowKeys.value = [];
    } else {
      expandedRowKeys.value = hasExpandKeys.value.map((i) => i);
    }
  };
  const handleExpand = (expanded, record) => {
    if (expanded) {
      expandedRowKeys.value.push(record.id);
    } else {
      const _index = expandedRowKeys.value.findIndex((item) => item == record.id);
      expandedRowKeys.value.splice(_index, 1);
    }
  };

  const loadTableData = async (params) => {
    const data = await getFormSortList();
    const flatTreeData = flatTree(data.result);
    hasExpandKeys.value = uniq(
      flatTreeData
        .filter((item) => item.parentNo && item.parentNo != '0')
        .map((item) => item.parentNo),
    );
    formSortTree.value = formatFormSortTree(cloneDeep(flatTreeData), '0');
    return { list: formatFormSortTree(cloneDeep(flatTreeData), '0') };
  };

  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}表单分类`,
        width: 700,
        onFinish: async (values) => {
          console.log('新增/编辑表单分类', values);
          record.id && (values.id = record.id);
          await (record.id ? editFormSort : createFormSort)(values);
          dynamicTableInstance.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: useFormSortSchema(),
      },
    });

    formRef?.updateSchema([
      {
        field: 'parentNo',
        componentProps: {
          treeDefaultExpandedKeys: ['0'].concat(record?.keyPath || []),
          treeData: ref([{ id: '0', name: '主目录', children: formSortTree.value }]),
        },
      },
    ]);

    formRef?.setFieldsValue({
      ...record,
    });
  };
  const delRowConfirm = async (record: TableListItem) => {
    await deleteFormSort({ id: record.id });
    dynamicTableInstance.reload();
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 220,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      actions: ({ record }) => [
        {
          label: '编辑',
          icon: h(EditOutlined),
          onClick: () => openMenuModal(record),
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
